package cn.clq.ymcc.exception;

import cn.clq.ymcc.constants.GlobalErrorEnum;
import cn.clq.ymcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author clqlongbao
 * @version 1.0
 * @description: 全局统一异常处理类
 * @date 2022/7/15 9:53
 */
@Component
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @description: 自定义的全局异常
     * @param: e
     * @return: cn.clq.ymcc.result.JSONResult
     * @author clqlongbao
     * @date: 2022/7/15 14:13
     */
    @ExceptionHandler(value = GlobalException.class)
    public JSONResult globalExceptionHandler(GlobalException e){
        log.error("GlobalException：{}",e);
        return JSONResult.error(e.getMessage(),e.getCode());
    }
    /**
     * @description: 运行时异常
     * @param: e
     * @return: cn.clq.ymcc.result.JSONResult
     * @author clqlongbao
     * @date: 2022/7/15 14:13
     */
    @ExceptionHandler(value = RuntimeException.class)
    public JSONResult runtimeExceptionHandler(RuntimeException e){
        if(e.getClass().getSimpleName().indexOf("AccessDeniedException") != -1){
            return JSONResult.error("没有权限访问");
        }
        log.error("RuntimeException：{}",e);
        return JSONResult.error(GlobalErrorEnum.SYSTEM_ERROR.getMessage(), GlobalErrorEnum.SYSTEM_ERROR.getCode());
    }

    /**
     * @description: 专门用于JSR303校验出错
     * @param: e
     * @return: cn.clq.ymcc.result.JSONResult
     * @author clqlongbao
     * @date: 2022/7/15 14:12
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        log.error("MethodArgumentNotValidException：{}",e);
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error->sb.append(error.getDefaultMessage()).append(","));
        return JSONResult.error(sb.toString());
    }
}
